import { useMessage } from './message';
export interface BasicWaterfallProps {
    // 查询条件表单对象，类型为any
    queryForm?: any;
    //图片数据
    imageArray?: any[];
    //是否加载完成
    isLoadOver?: boolean;
    //是否加载中
    isLoading?: boolean;
    //页码
    pagination: waterfallPages;
    //数据查询接口
    pageList?: (...arg: any) => Promise<any>;

}

export interface waterfallPages {
    size: number;
    current: number;
    total: number;
}

export function useWatetfall(options?: BasicWaterfallProps) {
    const defaultOptions: BasicWaterfallProps = {
        queryForm: {},
        imageArray: [],
        isLoading: false,
        isLoadOver: false,
        pagination: {
            size: 30,
            current: 1,
            total: 0
        } as waterfallPages,
    };
    //合并
    const mergeDefaultOptions = (options: any, props: any): BasicWaterfallProps => {
        for (const key in options) {
            if (!Object.getOwnPropertyDescriptor(props, key)) {
                props[key] = options[key]
            }
        }
        return props
    };
    const state = mergeDefaultOptions(defaultOptions, options);

    const getList = async () => {
        if (state.pageList) {
            state.imageArray = []
            state.isLoading = true
            const data = await state.pageList({
                ...state.queryForm,
                current: state.pagination?.current,
                size: state.pagination?.size,
            }).finally(() => state.isLoading = false)
            if (data && data.code == 0) {
                if (state.pagination.current == 1) {
                    state.imageArray = data.data.records || []
                } else {
                    state.imageArray = state.imageArray.concat(data.data.records)
                }
                state.pagination.total = data.data.total
                if (state.pagination.current * state.pagination.size >= state.pagination.total) {
                    state.isLoadOver = true
                }
            }
        }
    };
    //上拉加载
    const handlePullDown = () => {
        if (state.isLoadOver) return;
        state.pagination.current += 1;
        getList()
    };
    //页面滚动
    const handleScroll = (e: any) => {
        const scrollHeight = e.target.scrollHeight;
        const scrollTop = e.target.scrollTop;
        const clientHeight = window.innerHeight || Math.min(document.documentElement.clientHeight, document.body.clientHeight);
        if (scrollTop + clientHeight >= scrollHeight) {
            handlePullDown();
        }
    };
    const handleRefresh = () =>{
        state.isLoadOver = false
        state.pagination.current = 1;
        getList()
    }
    return {
        handlePullDown,
        handleScroll,
        getList,
        handleRefresh
    }

}